package com.gq.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONTokener;

import android.content.Context;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;


public class Client {
	
	private static final String TAG = Client.class.getSimpleName();
	private boolean parseJson = false;
	private Context context;
	
	public Client() {
	}
	
	public Client(Context context) {
		this.context = context;
	}
	
	public interface IClientListener {
		void onDone(boolean ok, Object ret);
	}
	
	public void excuteAndListen(String url, IClientListener listener) {
		excuteAndListen(url, listener, true);
	}
	
	public void excuteAndListen(String url, IClientListener listener, boolean parseJson) {
		DownloadTask task = new DownloadTask();
		task.setListener(listener);
		this.parseJson = parseJson;
		task.execute(url);
	}
	
	private class DownloadTask extends AsyncTask<String, Integer, Object> {
		
		private boolean success = false;
		private IClientListener listener;
		public void setListener(IClientListener listener) {
			this.listener = listener;
		}
		
		@Override
		protected Object doInBackground(String... urls) {
			Object ret = null;
			String url = urls[0];
			InputStream is = null;
			if (url.startsWith("asset://") && (context != null)) {
				String filename = url.substring("asset://".length());
				if (filename.startsWith("gzip:")) {
					filename = filename.substring("gzip:".length());
					try {
						is = new GZIPInputStream(context.getAssets().open(filename));
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else {
					try {
						is = context.getAssets().open(filename);
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
			} else if (url.startsWith("http")){
//				final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("android");
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet request = new HttpGet(urls[0]);
				try {
					HttpResponse response = httpClient.execute(request);
					final int statusCode = response.getStatusLine().getStatusCode();
					if (statusCode != HttpStatus.SC_OK) return null;
					final HttpEntity httpEntity = response.getEntity();
					Header encodingType = response.getFirstHeader("Content-Encoding");
					is = httpEntity.getContent();
					if (encodingType != null && "gzip".equals(encodingType.getValue())) {
						is = new GZIPInputStream(is, 1024);
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
				}
			}
			if (is == null) return ret;
			byte[] buff = new byte[4096];
			int byteRead = 0;
			StringBuilder sb = new StringBuilder();
			try {
				while((byteRead = (is.read(buff))) != -1) {
					sb.append(new String(buff, 0, byteRead));
				}
				is.close();
				success = true;
				return sb.toString();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return ret;
		}

		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			if (parseJson) {
				try {
					result = new JSONTokener(String.valueOf(result)).nextValue();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			listener.onDone(success, result);
		}
	}
}
